# coding: utf8

def refresh():
    logs = Logs()
    f = session.log_from
    q = session.log_quantity
    if f + q > len(logs.logs) or session.log_do_last:
        f = len(logs.logs) - q
        session.log_do_last = False
    if f < 0: f = 0
    session.log_from = f
    session.log_quantity = q
    response.js = ' '.join([
         'jQuery("#log_from").text("{}");'.format(f + 1),
         'jQuery("#log_to").text("{}");'.format(f + q),
         'jQuery("#log_len").text("{}");'.format(len(logs.logs)),
        ])
    return logs.get_logs_as_table(f, f + q)
    
def clear():
    with open('/sys/class/fw4/fw4_log/log_clear', 'w') as f:
        f.write('!')
    
    return first()
    
def first():
    session.log_from = 0
    return refresh()
    
def prev():
    session.log_from -= session.log_quantity
    return refresh()

def next():
    session.log_from += session.log_quantity
    return refresh()
    
def last():
    session.log_do_last = True
    return refresh()
    
def change_quantity():
    session.log_quantity = ast.literal_eval(request.args[0])
    return refresh()
